import React, { useEffect, useRef, useState } from "react";
import "./web.scss";
import { NavBar } from "antd-mobile";
import { Input, message } from "antd";
const { Search } = Input;
import {
    SmileOutline,
    PictureOutline,
    AudioOutline,
    AudioFill,
} from "antd-mobile-icons";
import { Popup } from "antd-mobile";
import { Upload } from "antd";
import axios from "axios";
import { useLocation, useNavigate } from "react-router-dom";
import emojis from "../../util/emojis.js";
import api from "../../util/api.js";

export default function Web() {
    let location = useLocation();
    const push = useNavigate();
    const [visible1, setVisible1] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();
    const back = () => {
        push(-1);
    };

    const [messages, setmessage] = useState([]);
    let users = `${location.state.friendid}`;
    const contentsRef = useRef(null);
    let socket = new WebSocket("ws://169.254.37.253:7777");

    const refs: any = useRef();
    const [text, settext] = useState(null);

    const change = (e: { target: { value: React.SetStateAction<null> } }) => {
        settext(e.target.value);
    };

    const onSearch = (value: string) => {
        if (value.trim() === "") {
            messageApi.open({
                type: "warning",
                content: "内容不能为空",
            });
        } else {
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(
                    JSON.stringify({
                        myid: users,
                        toid: location.state.myid,
                        context: value,
                        imgUrl: location.state.myavatar,
                    })
                );
                settext(null);
            }
        }
    };

    const source = axios.CancelToken.source();

    const getdata = async () => {
        try {
            let data2 = await axios.get(
                "http://localhost:3000/cwp/getmessage?myid=" +
                users +
                "&toid=" +
                "65516fd26ddb88b56724a2e3",
                {
                    cancelToken: source.token,
                }
            );
            setmessage(data2.data);
            if (contentsRef.current) {
                contentsRef.current.scrollTop = contentsRef.current.scrollHeight;
            }
        } catch (error) {
            if (axios.isCancel(error)) {
                // 请求被取消
                console.log("请求被取消");
            } else {
                // 处理其他错误
                console.error("Error fetching data:", error);
            }
        }
    };

    useEffect(() => {
        const socket = new WebSocket("ws://169.254.37.253:7777");
        socket.onopen = () => {
            console.log("连接成功");
            getdata();
            // 添加心跳机制
            setInterval(() => {
                if (socket.readyState === WebSocket.OPEN) {
                    socket.send(JSON.stringify({ type: "heartbeat" }));
                }
            }, 5000);
        };
        socket.onmessage = (e) => {
            getdata(); // 收到新消息时重新获取聊天记录
            console.log("实时更新");
        };
        return () => {
            console.log("断开了");
            socket.close();
        };
    }, []);

    useEffect(() => {
        if (contentsRef.current) {
            contentsRef.current.scrollTop = contentsRef.current.scrollHeight;
        }
    }, [messages]);

    const send = (emoji: any) => {
        const newText = text ? `${text} ${emoji}` : emoji;
        settext(newText);
        setVisible1(false);
    };

    const handleChange = (info: { file: { originFileObj: { name: any } } }) => {
        socket.send(
            JSON.stringify({
                myid: users,
                toid: location.state.myid,
                imgUrl: location.state.myavatar,
                img: "http://localhost:3000/upload/" + info.file.originFileObj.name,
            })
        );
    };

    // const [isRecording, setIsRecording] = useState(false);
    // const [audioChunks, setAudioChunks] = useState([]);
    // const mediaRecorder = useRef(null);
    // const handleStartRecording = async () => {
    //     try {
    //         const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    //         const mediaRecorderInstance = new MediaRecorder(stream);
    //         mediaRecorder.current = mediaRecorderInstance;

    //         mediaRecorderInstance.ondataavailable = (e) => {
    //             if (e.data.size > 0) {
    //                 setAudioChunks((chunks) => [...chunks, e.data]);
    //             }
    //         };
    //         mediaRecorderInstance.start();
    //         setIsRecording(true);
    //     } catch (error) {
    //         console.error('Error accessing microphone:', error);
    //     }
    // };

    // const handleStopRecording = () => {
    //     if (mediaRecorder.current && mediaRecorder.current.state !== 'inactive') {
    //         mediaRecorder.current.stop();
    //         setIsRecording(false);

    //         // 将音频数据发送到WebSocket服务器
    //         const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
    //         const formData = new FormData();
    //         formData.append('audio', audioBlob);

    //         axios.post(
    //             'http://localhost:3000/cwp/upload',
    //             formData
    //         ).then((res) => {
    //             console.log(res);
    //         }).catch((error) => {
    //             console.error(error);
    //         });
    //     }
    //     setAudioChunks([]);
    // };

    // 语音发送
    const [mediaRecorder, setmediaRecorder] = useState(null);
    const handleTouchStart = () => {
        navigator.mediaDevices
            .getUserMedia({ audio: true })
            .then((stream) => {
                const recorder = new MediaRecorder(stream);
                const audioChunks = [];
                recorder.addEventListener("dataavailable", (event) => {
                    if (event.data.size > 0) {
                        audioChunks.push(event.data);
                    }
                });
                recorder.start();
                setmediaRecorder(recorder);
                recorder.addEventListener("stop", () => {
                    const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
                    const formData = new FormData();
                    formData.append("audio", audioBlob);

                    api.post("/cwp/upload", formData)
                        .then((res) => {
                            socket.send(JSON.stringify({
                                myid: users,
                                toid: location.state.myid,
                                imgUrl: location.state.myavatar,
                                voice: res.data,
                            }))
                        })
                        .catch((error) => {
                            console.log("上传失败", error);
                        });
                });
            })
            .catch((error) => {
                console.error("无法访问麦克风", error);
            });
    };
    const handleTouchEnd = () => {
        mediaRecorder.stop();
    };

    return (
        <div className="websocketbox">
            {contextHolder}
            <Popup
                className="popup"
                visible={visible1}
                onMaskClick={() => {
                    setVisible1(false);
                }}
                onClose={() => {
                    setVisible1(false);
                }}
                bodyStyle={{ height: "40vh", overflow: "auto" }}
            >
                <div className="box">
                    {emojis.map(
                        (
                            emoji: {
                                unicode:
                                | string
                                | number
                                | boolean
                                | React.ReactElement<
                                    any,
                                    string | React.JSXElementConstructor<any>
                                >
                                | Iterable<React.ReactNode>
                                | React.ReactPortal
                                | null
                                | undefined;
                            },
                            index: React.Key | null | undefined
                        ) => (
                            <div onClick={() => send(emoji.unicode)} key={index}>
                                {emoji.unicode}
                            </div>
                        )
                    )}
                </div>
            </Popup>
            <div className="head">
                <NavBar onBack={back}>{location.state.friendname}</NavBar>
            </div>

            <div className="content" ref={contentsRef}>
                {messages.map((item, index) => {
                    if (item.myid === `${location.state.myid}` && item.toid === users) {
                        return (
                            <div className="websocket" key={item._id}>
                                <div className="left">
                                    <img src={item.imgUrl} alt="" />
                                </div>
                                <div className="right">
                                    <div>
                                        {item.voice ? (
                                            // 渲染语音
                                            <audio controls>
                                                <source src={item.voice} type="audio/mpeg" />
                                                Your browser does not support the audio element.
                                            </audio>
                                        ) : item.img ? (
                                            // 渲染图片
                                            <img src={item.img} alt="" />
                                        ) : (
                                            // 渲染文本内容
                                            <>{item.context}</>
                                        )}
                                    </div>
                                </div>
                            </div>
                        );
                    } else if (
                        item.myid === users &&
                        item.toid === `${location.state.myid}`
                    ) {
                        return (
                            <div className="websocket2" key={item._id}>
                                <div className="right">
                                    <div>
                                        {item.voice ? (
                                            // 渲染语音
                                            <audio controls>
                                                <source src={item.voice} type="audio/mpeg" />
                                            </audio>
                                        ) : item.img ? (
                                            // 渲染图片
                                            <img src={item.img} alt="" />
                                        ) : (
                                            // 渲染文本内容
                                            <>{item.context}</>
                                        )}
                                    </div>
                                </div>
                                <div className="left">
                                    <img src={item.imgUrl} alt="" />
                                </div>
                            </div>
                        );
                    }
                })}
            </div>

            <div className="bottom">
                <Search
                    placeholder="快跟好友说点什么吧"
                    allowClear
                    enterButton="发送"
                    size="large"
                    value={text}
                    ref={refs}
                    onChange={change}
                    onSearch={onSearch}
                />
                <div className="emoji">
                    <button onTouchStart={handleTouchStart}
                        onTouchEnd={handleTouchEnd}
                    >
                        <AudioFill />
                    </button>
                    <SmileOutline
                        onClick={() => {
                            setVisible1(true);
                        }}
                        fontSize={"30px"}
                    />
                    <Upload
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        action="http://localhost:3000/cwp/getImg"
                        beforeUpload={(file) => {
                            handleChange({ file: { originFileObj: file } });
                            // return false;  // 阻止自动上传
                        }}
                    >
                        <PictureOutline />
                    </Upload>
                </div>
            </div>
        </div>
    );
}
